<?php

namespace service\client;

class TcpClient
{

    private $client;

    private static $_instance;

    public function __construct()
    {
        $this->client = stream_socket_client('tcp://127.0.0.1:8888');
    }

    public static function getInstance(){
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    public function send($request)
    {
        fwrite($this->client, json_encode($request)."\n"); // text协议末尾有个换行符"\n"
        $result = fgets($this->client, 10240000);
        $result = json_decode($result, true);

        return $result;
    }
}